// ignore_for_file: prefer_const_literals_to_create_immutables, prefer_const_constructors

 
import 'dart:async';
import 'dart:math';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/mine/widget/QGLogOutWidgetappupdata.dart';

import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:junyeyishu/ui/home/widgets/QGBannerWidget.dart';
import 'package:junyeyishu/ui/home/widgets/QGNFTWidget.dart';
import 'package:junyeyishu/ui/home/widgets/QGTypeSwitchWidget.dart';
import '/utils/utils.dart';

class QGHomePage extends StatefulWidget {
  const QGHomePage({super.key});
  @override
  State<QGHomePage> createState() => _QGHomePageState();
}

class _QGHomePageState extends State<QGHomePage> {
  int type = 0;
  EasyRefreshController refreshController = EasyRefreshController();

  Map data = {};

  List? goods;
  bool animSwitch = true;

  @override
  void initState() {
    super.initState();

    eventBus.on<EventMainTabRefresh>().listen((event) {
      if (event.index != 0) return;
      onRefresh();
    });


     onRefresh();


  }

  
  


  onRefresh() async {
    var res = await Network.post(url_index_getCache);

    if (!res.success) {
      toast(res.msg);
      return false;
    }

    updateCurrentTime(res.data!=null ? res.data["curTime"]:null);

    data["goods"] = res.data?["tab_type_1"];
    data["b_goods"] = res.data?["tab_type_2"];
    data["pre_goods"] = res.data?["tab_type_3"];
    data["banner"] = res.data?["banner"];


    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
  
    return Scaffold(
        backgroundColor: Color(0XFF0c1012),
        body: EasyRefresh( 
          controller: refreshController,
          onRefresh: onRefresh,
          child: NotificationListener(
            onNotification: onNotification,
            child: SingleChildScrollView(
              child: Stack(
                children: [
                  QGImage(
                    asset: "home_bg",
                    width: 375.rpx,
                    height: 390.rpx,
                  ),
                  Column(
                    children: [
                      SizedBox(height: max(kSafeTop, 50)),
                      buildBanner(),
                      SizedBox(height: 30.rpx),

                      Padding(padding: EdgeInsets.symmetric(horizontal: 15),
                      child:  Stack(
                        children: [
                          QGImage(
                            asset: "hong_huodong", width: kScreenWidth
                          ),

                          Positioned(
                            right: 0,
                            left: 0,
                            child:Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: (){
                                    Navigator.of(context).pushNamed(PageSynthesisList);
                                  },
                                  child: Container(
                                    width: 170.rpx,
                                    height: 75.rpx,
                                  ),
                                ),

                                GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: (){
                                    Navigator.of(context).pushNamed(PageColorfulSynthesisList);
                                  },
                                  child: Container(
                                    width: 160.rpx,
                                    height: 75.rpx,
                                  ),
                                ),
                            
                              ],
                            ) 
                          ),
                          Positioned(
                            top: 80.rpx,
                            right: 0,
                            left: 0,
                            child:Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                GestureDetector(behavior: HitTestBehavior.opaque,
                                 onTap: (){
                                    Navigator.of(context).pushNamed(PageDisplaceList);
                                  },
                                child: Container(
                              width: 110.rpx,
                              height: 75.rpx,
                            ),
                                )
                              ,
                             GestureDetector(behavior: HitTestBehavior.opaque,
                                 onTap: (){
                                    Navigator.of(context).pushNamed(pageSettingPage);
                                  },
                                child: Container(
                              width: 100.rpx,
                              height: 75.rpx,
                            ),
                                ),
                            GestureDetector(behavior: HitTestBehavior.opaque,
                                 onTap: (){
                                  toDownload();
                                   
                                  },
                                child: Container(
                              width: 110.rpx,
                              height: 75.rpx,
                            ),
                                )
                              ],
                            ) 
                          ),

                        ],
                      ),
                      ),

                      // inReview() ? Container() : buildMenu(),
                      SizedBox(height: 30.rpx),
                      buildContent(),
                    ],
                  ),
               
               
                ],
              ),
            ),
          ),
        ));
  }

  // 列表内容
  buildContent() {
    return Stack(
      children: [
        // buildImage(),
        Column(children: [
          buildSwitch(),
          SizedBox(height: 10.rpx),
          buildList(),
        ])
      ],
    );
  }

  buildBanner() {
    dynamic listData = data["banner"] ?? [];

    if (listData.isEmpty) {
      return Container(height: 160.rpx);
    }

    return Container(
      height: 160.rpx,
      margin: EdgeInsets.fromLTRB(15, 0, 15, 0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.rpx),
        child: QGBannerWidget(
            animSwitch: animSwitch,
            count: listData.length,
            itemBuilder: (context, index) {
              var itemData = listData[index];
              return GestureDetector(
                onTap: () {
                  String url = itemData["url"] ?? "";

                  if (url.startsWith("http")) {
                    Navigator.of(context)
                        .pushNamed(PageWebView, arguments: url);
                  }
                  if(url=='mingren'){
                     Navigator.of(context)
                        .pushNamed(PageQGInviteMinPage);
                  }
                  

                },
                child: Container(
                  child: QGImage(url: itemData["pic"]),
                ),
              );
            },
            onPageChanged: (idx) {}),
      ),
    );
  }

  buildMenu() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            buildMenuItem("home_menu_synthesis", "合成活动",
                page: PageSynthesisList),
            buildMenuItem("home_menu_colorful", "缤纷活动",
                page: PageColorfulSynthesisList),
            buildMenuItem("home_menu_displace", "分解活动", page: PageDisplaceList),
            buildMenuItem("home_menu_download", "APP下载", action: toDownload),
          ],
        ),
      ],
    );
  }

  buildMenuItem(imageName, title, {page = "", action}) {
    return GestureDetector(
      onTap: () {
        if (action != null) {
          action();
        } else if (!page.isEmpty) {
          Navigator.of(context).pushNamed(page);
        }
      },
      child: Container(
        width: 50.rpx,
        color: Colors.transparent,
        child: Stack(
          children: [
            Container(
              alignment: Alignment.center,
              child: Column(
                children: [
                  QGImage(asset: imageName, width: 46.rpx),
                  SizedBox(height: 8.rpx),
                  Text(
                    title,
                    style: TextStyle(
                        color: const Color(0xFFFFFFFF),
                        fontSize: 11.rpx,
                        fontWeight: FontWeight.normal),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildImage() {
    return QGImage(asset: "home_tab_bg", width: kScreenWidth);
  }

  buildSwitch() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        inReview()
            ? QGTypeSwitchWidget(
                current: type,
                items: ["数字资产"],
                underline: true,
                paddingLen: 22,
                onSwitch: (index) {
                  type = index;
                  setState(() {});
                  onRefresh();
                },
              )
            : QGTypeSwitchWidget(
                current: type,
                items: ["数字资产", "数字盲盒"],
                underline: true,
                paddingLen: 22,
                onSwitch: (index) {
                
                    type = index;

                  setState(() {});
                  onRefresh();
                },
              ),
      ],
    );
  }

  buildList() {
    var list = data[type == 0
            ? "goods"
            : type == 1
                ? "pre_goods"
                : "b_goods"] ??
        [];

    return ListView.builder(
        padding: EdgeInsets.zero,
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: inReview() ? min(list.length, 1) : list.length,
        itemBuilder: (context, idx) {
          var data = list?[idx];
          return GestureDetector(
              onTap: () {
                toDetail(data["pid"]);
              },
              child: QGHomeCell(data: data));
        });
  }

  bool onNotification(note) {
    final offset = note.metrics.pixels.toInt();
    if (offset < -10 && animSwitch) {
      animSwitch = false;
      setState(() {});
    } else if (offset > -10 && !animSwitch) {
      animSwitch = true;
      setState(() {});
    }
    return false;
  }

  toInvite() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageInvite);
  }

  toDownload() {
    // if(!kIsWeb){
    //   launchUrl(Uri.parse("${Network.h5URL}download.html"),
    //     mode: LaunchMode.externalApplication);
    // }else{
    //   Navigator.of(context).pushNamed(PageQGDown);
    // }
      Navigator.of(context).pushNamed(PageQGDown);

  }

  toDetail(args) {
    Navigator.of(context).pushNamed(
        inReview() ? PageReviewNFTDetail : PageNFTDetail,
        arguments: args);
  }
}
